import { FC, useCallback, useEffect, useState } from 'react';
import { Card, Table, Button, Space, Tag, Input, Row, Col, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
import { industryReportApi } from 'services/industry-report';
import { IndustryReportItem, IndustryReportParams } from 'types/industry-report';
import MainLayout from 'components/MainLayout';
import dayjs from 'dayjs';

import styles from './style/index.module.css';

const ReportList: FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [reports, setReports] = useState<IndustryReportItem[]>([]);
  const [keyword, setKeyword] = useState('');

  // 添加分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取报告列表数据
  const fetchReports = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const params: IndustryReportParams = {
          page,
          pageSize,
        };
        if (keyword) params.keyword = keyword;

        const res = await industryReportApi.getIndustryReportList(params);

        if (res.code === 200) {
          setReports(res.data.results);

          setPagination((prev) => ({
            ...prev,
            current: page,
            total: res.data.count,
          }));
        }
      } catch (error) {
        console.error('获取报告列表失败:', error);
      } finally {
        setLoading(false);
      }
    },
    [keyword]
  );

  // 监听筛选条件变化
  useEffect(() => {
    fetchReports(1, pagination.pageSize);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyword]);

  // 修改搜索处理函数
  const handleSearch = (value: string) => {
    setKeyword(value);
  };

  const handleDelete = (record: IndustryReportItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除报告"${record.title}"吗？`,
      onOk: () => {
        industryReportApi.deleteIndustryReport(record.id).then(res => {
          if (res.code === 200) {
            message.success('删除成功');
            fetchReports(1, pagination.pageSize);
          }
        });
      },
    });
  };

  const typeMap = {
    industry: { text: '产业报告', color: 'blue' },
    phase: { text: '阶段报告', color: 'purple' },
    custom: { text: '自定义报告', color: 'green' },
  };

  const statusMap = {
    draft: { text: '草稿', color: 'orange' },
    published: { text: '已发布', color: 'green' },
    archived: { text: '已存档', color: 'blue' },
  };

  const columns: ColumnsType<IndustryReportItem> = [
    {
      title: '报告标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <a onClick={() => navigate(`/report/detail/${record.id}`)}>
          {text}
        </a>
      ),
    },
    // {
    //   title: '报告类型',
    //   dataIndex: 'type',
    //   key: 'type',
    //   render: (type: keyof typeof typeMap) => (
    //     <Tag color={typeMap[type].color}>{typeMap[type].text}</Tag>
    //   ),
    // },
    // {
    //   title: '作者',
    //   dataIndex: 'author',
    //   key: 'author',
    // },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '',
    },
    {
      title: '产业方向',
      dataIndex: 'industry',
      key: 'industry',
      render: (industry) => {
        if (!industry) return '-';
        return <Tag color="magenta">{industry}</Tag>;
      },
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   key: 'status',
    //   render: (status: keyof typeof statusMap) => status ? (
    //     <Tag color={statusMap[status].color}>{statusMap[status].text}</Tag>
    //   ) : '',
    // },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            onClick={() => navigate(`/report/detail/${record.id}`)}
          >
            查看
          </Button>
          {/* <Button
            type="link"
            onClick={() => navigate(`/report/edit/${record.id}`)}
          >
            编辑
          </Button> */}
          <Button
            type="link"
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <MainLayout>
      <Card
        title="报告管理"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/report/industry')}
            >
              新建报告
            </Button>
          </Space>
        }
      >
        <div className={styles.toolbar}>
          <Row gutter={16} align="middle">
            <Col flex="auto">
              <Input.Search
                placeholder="搜索报告标题"
                onSearch={handleSearch}
                style={{ width: 300 }}
                allowClear
              />
            </Col>
          </Row>
        </div>

        <Table<IndustryReportItem>
          columns={columns}
          dataSource={reports}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              fetchReports(page, pageSize);
            },
          }}
        />
      </Card>
    </MainLayout>
  );
};

export default ReportList;
